package cn.sangyy.gift.exception.handler;

import cn.sangyy.gift.common.util.AjaxResult;
import cn.sangyy.gift.common.util.code.CodeEnum;
import cn.sangyy.gift.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author SangYY
 * @date: 2023/03/30/15:48
 */
//统一异常处理
@RestControllerAdvice
@Slf4j
public class UnifyExceptionHandler {

    //已知异常
    @ExceptionHandler(BusinessException.class)
    AjaxResult businessExceptionHandler(BusinessException b){
        b.printStackTrace();
        log.error(b.getMessage());
        return AjaxResult.me().setCode(b.getCode()).setMessage(b.getMessage());
    }

    //已知异常 jsr303校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException m){
        m.printStackTrace();
        BindingResult result = m.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            sb.append(fieldError.getDefaultMessage()+",");
        });
        m.printStackTrace();
        log.error(m.getMessage());
        String message = sb.substring(0, sb.length() - 2);
        return AjaxResult.me().setCode(CodeEnum.PARAM_ERROR.getCode()).setMessage(message);
    }

    //未知异常
    @ExceptionHandler(Exception.class)
    AjaxResult exceptionHandler(Exception e){
        log.error(e.getMessage());
        e.printStackTrace();
        return AjaxResult.me().setCode(CodeEnum.SERVICE_ERROR.getCode()).setMessage(CodeEnum.SERVICE_ERROR.getMessage());
    }
}
